package cdu.javaendwork.Controller.Admin.AdoptionMore;

import cdu.javaendwork.model.sqlModel.Post;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.service.Impl.AdoptionMore.PostServiceImpl;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.AdoptionMore.PostService;
import cdu.javaendwork.service.Interface.User.UserService;
import cdu.javaendwork.util.pageHelp.PageHelper;
import cdu.javaendwork.util.pageHelp.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@WebServlet("/admin/post_list")
public class PostsController extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset = utf-8");
        req.setCharacterEncoding("UTF-8");

        String sPage = req.getParameter("page");
        String postKeys=req.getParameter("postKeys");
        req.setAttribute("postKey",postKeys);
        System.out.println("postKeys: " + postKeys);
        int pageSize=3;
        int pageIndex = (sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);
        PageHelper pageHelper = new PageHelper();
        PageInfo pageInfo = pageHelper.all("Post",pageIndex,pageSize);

        UserService userService=new UserServiceImpl();

        Set<Integer> set = new HashSet<>();
        List<User> userList=new ArrayList<>();
        PostService postService=new PostServiceImpl();
        List<Post> postList=new ArrayList<>();
        if(postKeys==null||postKeys.equals("")) {
            postList = postService.AdminPostLimit(pageIndex, pageSize);
        }else {
            pageInfo=pageHelper.filter("Post","(title like '%" + postKeys + "%' or content like '%"+postKeys+"%' )",pageIndex,pageSize);
            postList=postService.AdminFilterByTitleAndContentLimit(postKeys,pageIndex,pageSize);
        }
        req.setAttribute("posts",postList);
        for (Post post:postList){
            int userid = post.getUserid();
            if(set.contains(userid)) continue;
            User user= userService.findById(userid);
            userList.add(user);
            set.add(userid);
        }


        req.setAttribute("userList",userList);
        req.setAttribute("pageInfo",pageInfo);

        req.getRequestDispatcher("post_manage.jsp").forward(req,resp);
    }
}
